package com.example.xwuser.api;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.example.xw.common.entity.User;
import com.example.xw.common.service.UserService;
import com.example.xw.common.service.WeiboService;
import com.example.xw.common.vo.Result;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RefreshScope
public class UserApi {
    @Autowired
    @Qualifier("myUserServiceImpl")
    public UserService userService;
    @Value("${my.upload_dir}")
    private String uploadDir;
    @Autowired
    private WeiboService weiboService;

    @PostMapping("/api/reg")
    @GlobalTransactional
    public ResponseEntity<Result<User>> reg(String nickname, String loginname
            , String loginpwd, MultipartFile photofile) throws IOException {
        String photoName = null;
        if(!photofile.isEmpty()){
            photoName = photofile.getOriginalFilename();
            photoName = UUID.randomUUID().toString()+photoName.substring(photoName.lastIndexOf("."));

            File uploadFile = new File(uploadDir);
            if(!uploadFile.exists()){
                uploadFile.mkdirs();
            }
            photofile.transferTo(new File(uploadDir+"/"+photoName));
        }
        Result<User> r = userService.reg(nickname,loginname,loginpwd,photoName);
        if(r.getCode() == 2000){
            weiboService.weiboAdd(loginname,"新人报道","大家好，我是"+nickname+"，欢迎大家关注我。","");
        }
        r.getData().setLoginpwd(null);
        return ResponseEntity.ok(r);
    }
    @SentinelResource(value = "/login",fallback = "loginBlockHandler")
    @RequestMapping("/api/login")
    public ResponseEntity<Result<User>> login(String loginname, String loginpwd, HttpSession session){
        Result<User> r = userService.login(loginname,loginpwd);
        if(r.getCode() == 2000){
            User user = r.getData();
            user.setLoginpwd(null);
            session.setAttribute("user",r.getData());
            return ResponseEntity.ok(r);
        }
        return ResponseEntity.status(401).body(r);
    }

    public ResponseEntity<Result<String>> loginBlockHandler(String loginname, String loginpwd, HttpSession session, Throwable e){
        return ResponseEntity.status(500).body(new Result<>(6000,null,"服务器繁忙，请稍后再试"));
    }


}
